package com.blocks.mq.listener.example.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.blocks.mq.listener.entity.Student;
import com.blocks.mq.listener.example.service.ExampleTxtWriterService;
import com.blocks.mq.listener.example.service.ExampleXlsxWriterService;
import com.blocks.mq.listener.repository.StudentRepository2;
import com.zut.blocks.base.mq.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lxd
 * @date 2020/12/4 23:59
 */
@Slf4j
@Component
public class ExampleTopicConsumer {

    @Resource
    StudentRepository2 studentRepository2;

    @Resource
    ExampleTxtWriterService exampleTxtWriterService;

    @Resource
    ExampleXlsxWriterService exampleXlsxWriterService;

    @JmsListener(destination="${spring.activemq.example-topic}", containerFactory="topicListener")
    public void readActiveTopic(String message) {
        Message msg = JSON.parseObject(message, Message.class);
        if (msg.getType().equals(Message.MessageType.database)) {
            Student student = JSON.parseObject(msg.getData(), Student.class);
            student.setId(null);
            studentRepository2.save(student);
        } else if (msg.getType().equals(Message.MessageType.xlsx)) {
            List<List<String>> data = JSONArray.parseObject(msg.getData(), new TypeReference<List<List<String>>>() {});
            exampleXlsxWriterService.writeExcel(data, msg.getFilePath());
        } else if (msg.getType().equals(Message.MessageType.txt)) {
            exampleTxtWriterService.writeTxt(msg.getData(), msg.getFilePath());
        } else {
            log.error("unsupported data format: {}", message);
        }
    }
}
